﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq;
using System.Text;

using System.Transactions;
using MINERP.BLL.Common;
using MINERP.COM;
using MINERP.DAL;
using MINERP.DAL.PhotoRindGrid;
using MINERP.MODEL.FoundationModel;

using System.Data.SqlClient;
using System.Data;
using MINERP.DAL.CommonDAL;
using MINERP.MODEL.PhotoRindGrid;


namespace MINERP.BLL.PhotoRindGrid
{
    public class PhotoRindGridBLL2
    {
        private MINERP.DAL.PhotoRindGrid.PhotoRindGridDAL _dal = new PhotoRindGridDAL();
        MINERP.DAL.CommonDAL.OrderInfoDAL _orderDal = new MINERP.DAL.CommonDAL.OrderInfoDAL();
        private newSampleYPDBEntities dataBase = null;
        public PhotoRindGridBLL2()
        {
            dataBase = new newSampleYPDBEntities();
        }

        /// <summary>
        /// 取得所有可用分区1
        /// </summary>
        /// <returns></returns>
        public List<GridSubArea_Info> GetSubareaUseful()
        {
            List<GridSubArea_Info> infoList = new List<GridSubArea_Info>();
            int intPhotoSubAreas = (int)SubAreaType.Photo;
            List<GridSubArea> subareas = dataBase.GridSubArea.Where(p => p.Type == intPhotoSubAreas).ToList();

            foreach (GridSubArea list in subareas)
            {
                GridSubArea_Info info = new GridSubArea_Info()
                {
                    SubAreaID = list.SubAreaID,
                    HeightNum = list.heightNum,
                    IsUseful = list.isUseful,
                    NameHeadChar = list.nameHeadChar,
                    SubAreaName = list.SubAreaName,
                    Type = list.Type,
                    WidthNum = list.widthNum,
                    OutTimeAlarmTime = (double)list.OutTimeAlarmTime,
                    GridClearTime = (double)list.GridClearTime
                };
                infoList.Add(info);
            }
            return infoList;
        }
        /// <summary>
        /// 根据Id取得分区信息
        /// </summary>
        /// <param name="inSubAreaId"></param>
        /// <returns></returns>
        public GridSubArea_Info GetOneSunAreaById(int inSubAreaId)
        {
            GridSubArea subArea = dataBase.GridSubArea.FirstOrDefault(p => p.SubAreaID == inSubAreaId);
            GridSubArea_Info info = new GridSubArea_Info()
            {
                SubAreaID = subArea.SubAreaID,
                HeightNum = subArea.heightNum,
                IsUseful = subArea.isUseful,
                NameHeadChar = subArea.nameHeadChar,
                SubAreaName = subArea.SubAreaName,
                Type = subArea.Type,
                WidthNum = subArea.widthNum,
                OutTimeAlarmTime = (double)subArea.OutTimeAlarmTime,
                GridClearTime = (double)subArea.GridClearTime
            };
            return info;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="inSubAreaId"></param>
        /// <returns></returns>
        public List<GridView> GetGridBySubAreaId(int inSubAreaId)
        {

            List<Grid> grids = dataBase.Grid.Where(p => p.GridSubArea.SubAreaID == inSubAreaId).ToList();
            List<GridView> views = new List<GridView>();
            views = ChangerToView(grids);
            //return info;
            return views;


        }
        /// <summary>
        /// 转化成现实实体
        /// </summary>
        /// <param name="lists"></param>
        /// <returns></returns>
        public List<GridView> ChangerToView(List<Grid> lists)
        {
            //MINERP.DAL.PhotoRindGrid.OrderInfoDAL oiDal = new MINERP.DAL.PhotoRindGrid.OrderInfoDAL();

            //MINERP.DAL.CommonDAL.OrderInfoDAL oiDal = new MINERP.DAL.CommonDAL.OrderInfoDAL();
            List<GridView> views = new List<GridView>();
            foreach (Grid list in lists)
            {
                //if (!list.GridSubAreaReference.IsLoaded)
                //{
                //    list.GridSubAreaReference.Load();

                //}
                GridView view = new GridView();
                //view.PhotoGridInfo = new Grid_Info() { SomeId = list.SomeId, GridId = list.GridId, FirstEnterTime = (DateTime)list.FirstEnterTime, GridName = list.GridName, SubAreaId = list.GridSubArea.SubAreaID, Status = (int)list.Status };
                view.PhotoGridInfo = new Grid_Info() { SomeId = list.SomeId, GridId = list.GridId, FirstEnterTime = (DateTime)list.FirstEnterTime, GridName = list.GridName, SubAreaId = list.GridSubArea.SubAreaID, Status = (int)list.Status };
                orderInfo product = null;
                if (list.Status == (int)GridStatus.use)
                {
                    product = _dal.GetProductById(list.SomeId);
                }

                if (product != null)
                {
                    ///加载其他产品相关信息
                    view.OrderProductInfo = new OrderInfo_Info()
                    {
                        OrderProductName = product.OrderProductName,
                        PageNum = product.productNum,
                        CtmName = product.CtmName,
                        OrderProductCode = product.OrderProductCode,
                        OrderProductId = product.OrderProductId
                    };
                    if (!product.Tb_OrderBagReference.IsLoaded)
                    {
                        product.Tb_OrderBagReference.Load();
                    }
                    if (!product.Tb_OrderBag.ShopReference.IsLoaded)
                    {
                        product.Tb_OrderBag.ShopReference.Load();
                    }


                    //view.ShopInfo = new Shop_Info() { ShopId = product.Tb_OrderBag.Shop.ShopId, ShopName = product.Tb_OrderBag.Shop.shopName };
                    //view.OrderBagInfo = new Tb_OrderBag_Info() { BagName = product.Tb_OrderBag.BagName, BagCode = product.Tb_OrderBag.BagCode };

                    //view.SubAreaInfo = new GridSubArea_Info() { SubAreaName = list.GridSubArea.SubAreaName };
                    //取得数量
                   // List<photoInfo> photos = _dal.GetPhotoOfProduct(list.SomeId);
                    List<photoInfo> photos = dataBase.photoInfo.Where(p => p.orderInfo.OrderProductId == list.SomeId).ToList();
                    view.Count = photos.Count();
                    int curr = 0;
                    foreach (photoInfo info in photos)
                    {
                        //GridRecord gridRecords = _dal.GetGridRecordByGridId(list.GridId, info.photoId);
                        GridRecord gridRecords = dataBase.GridRecord.Where(string.Format("it.Grid.GridId={0} and it.SomeId={1}", list.GridId, info.photoId)).FirstOrDefault();
                        if (gridRecords != null)
                        {
                            curr += gridRecords.Num;
                        }
                        view.Curr = curr;
                    }
                    //view.ShopInfo = new Shop_Info() { ShopName = oiDal.GetShopName(list.GridId) };
                    //view.ShopName = product.Tb_OrderBag.Shop.shopName;
                }

                views.Add(view);

            }
            return views;
        }

        /// <summary>
        /// 根据Id取得格子信息
        /// </summary>
        /// <param name="gridId"></param>
        /// <returns></returns>
        public Grid_Info GetGridById(int gridId)
        {
            //Grid grid = _dal.GetGridById(gridId);
            Grid grid = dataBase.Grid.FirstOrDefault(p => p.GridId == gridId);
            //if (!grid.GridSubAreaReference.IsLoaded)
            //{
            //    grid.GridSubAreaReference.Load();
            //}
            //orderInfo product = _dal.GetProductById(grid.SomeId);
            //Grid_Info info = new Grid_Info() { GridId = grid.GridId, SomeId = grid.SomeId, FirstEnterTime = (DateTime)grid.FirstEnterTime, GridName = grid.GridName, SubAreaId = grid.GridSubArea.SubAreaID, Status = (int)grid.Status };
            Grid_Info info = new Grid_Info() { GridId = grid.GridId, SomeId = grid.SomeId, FirstEnterTime = (DateTime)grid.FirstEnterTime, GridName = grid.GridName, Status = (int)grid.Status };
            return info;
        }
        /// <summary>
        /// 取得格子相关详细信息
        /// </summary>
        /// <param name="inGridId"></param>
        /// <returns></returns>
        public List<GridView> GetShopInfo(int inGridId)
        {
            //Grid grid = _dal.GetGridById(inGridId);
            Grid grid = dataBase.Grid.FirstOrDefault(p => p.GridId == inGridId);
            List<Grid> lists = new List<Grid>();

            lists.Add(grid);
            return ChangerToView(lists);
        }
        /// <summary>
        /// 取得格子头部相关详细信息
        /// </summary>
        /// <param name="inGridId"></param>
        /// <returns></returns>
        public PhotoGridOrderHeadInfo GetHeadInfo(int orderProductid)
        {
            PhotoGridOrderHeadInfo oiheadinfo = new PhotoGridOrderHeadInfo();
            if (orderProductid != 0)
            {
                MINERP.DAL.PhotoRindGrid.OrderInfoDAL oiDal = new MINERP.DAL.PhotoRindGrid.OrderInfoDAL();
                oiheadinfo = oiDal.GetOrderHeadInfoById(orderProductid);

            }
            return oiheadinfo;
        }

        public PhotoGridOrderHeadInfo GetHeadInfoStr(string inBarCode)
        {
            photoInfo info = dataBase.photoInfo.FirstOrDefault(p=>p.PhotoBarCode==inBarCode);
            info.orderInfoReference.Load();
            orderInfo oi = info.orderInfo;
            PhotoGridOrderHeadInfo oiheadinfo = new PhotoGridOrderHeadInfo();
            if (oi.OrderProductId != 0)
            {
                MINERP.DAL.PhotoRindGrid.OrderInfoDAL oiDal = new MINERP.DAL.PhotoRindGrid.OrderInfoDAL();
                oiheadinfo = oiDal.GetOrderHeadInfoById(oi.OrderProductId);

            }
            return oiheadinfo;
        }
        ///// <summary>
        ///// 取得格子头部相关详细信息
        ///// </summary>
        ///// <param name="inGridId"></param>
        ///// <returns></returns>
        //public PhotoGridOrderHeadInfo GetHeadInfo(string  inPhotoBarCode)
        //{

        //    PhotoGridOrderHeadInfo oiheadinfo = new PhotoGridOrderHeadInfo();
        //    if (string.IsNullOrEmpty(inPhotoBarCode))
        //    {
               
        //        MINERP.DAL.PhotoRindGrid.OrderInfoDAL oiDal = new MINERP.DAL.PhotoRindGrid.OrderInfoDAL();
        //        oiheadinfo = oiDal.GetOrderHeadInfoById(orderProductid);

        //    }
        //    return oiheadinfo;
        //}

        /// <summary>
        /// 
        /// 取得照片列表
        /// </summary>
        /// <param name="inGridID"></param>
        /// <returns></returns>
        public List<PhotoView> GetPhotosByGrid(int inGridID)
        {
            //Grid grid = _dal.GetGridById(inGridID);
            Grid grid = dataBase.Grid.FirstOrDefault(p => p.GridId == inGridID);

            //orderInfo product = _dal.GetProductById(grid.SomeId);
            orderInfo product = dataBase.orderInfo.FirstOrDefault(p => p.OrderProductId == grid.SomeId);
            if (product == null)
            {
                return null;
            }
            if (!product.photoInfo.IsLoaded)
            {
                product.photoInfo.Load();
            }
            //List<photoInfo> photoInfos = _dal.GetPhotoByProductId(product.OrderProductId);
            List<PhotoView> photoViews = new List<PhotoView>();
            foreach (photoInfo list in product.photoInfo)
            {

                PhotoView view = new PhotoView();
                view.PhotoInfo = new PhotoInfo_Info() { Height = list.Height, Width = list.Width, PhotoName = list.photoName, PhotoBarCode = list.PhotoBarCode, Status = list.status, TotalNum = (int)list.TotalNum, PicPath = list.picPath,PhotoId=list.photoId };
                printer pr = new printer();
                //pr = _dal.GetPrinterById((int)list.printerId);
                pr = dataBase.printer.FirstOrDefault(p => p.PrinterID == list.printerId);
                if (pr != null)
                {
                    view.PrinterName = pr.PName;
                }
                else
                {
                    view.PrinterName = "";
                }
                if (!list.paperFaceReference.IsLoaded)
                {
                    list.paperFaceReference.Load();
                }
                if (!list.paperTypeReference.IsLoaded)
                {
                    list.paperTypeReference.Load();
                }
                //GridRecord record = _dal.GetGridRecordByGridId(inGridID, list.photoId);
                GridRecord record = dataBase.GridRecord.Where(string.Format("it.Grid.GridId={0} and it.SomeId={1}", inGridID, list.photoId)).FirstOrDefault();
                if (record != null)
                {
                    view.GridRecordInfo = new GridRecord_Info() { Num = record.Num };
                }
                else
                {
                    view.GridRecordInfo = new GridRecord_Info() { Num = 0 };
                }
                view.PaperFaceInfo = new PaperFace_Info() { Name = list.paperFace.Name };
                view.PaperTypeInfo = new PaperType_Info() { Name = list.paperType.Name };
                photoViews.Add(view);
            }
            return photoViews;
        }
        /// <summary>
        /// 分配格子
        /// </summary>
        /// <param name="inPhotoBarcode"></param>
        /// <param name="inNum"></param>
        /// <param name="inUserId"></param>
        /// <returns>返回格子Id</returns>
        public int AssionGrid(string inPhotoBarcode, int inNum, int inUserId, int inSubAreaId, int inCurrTechID)
        {
            int intPhotoPrinted = (int)PhotoStatus.Printed;
            int intPhotoFenPian = (int)PhotoStatus.FenPian;
            //photoInfo photoInfo = _dal.GetPhotoByBarCode(inPhotoBarcode); //照片信息
            photoInfo photoInfo = dataBase.photoInfo.Where(p => p.PhotoBarCode == inPhotoBarcode && (p.status == intPhotoFenPian || p.status == intPhotoPrinted)).OrderByDescending(p => p.photoId).FirstOrDefault(); //照片信息
            if (!photoInfo.orderInfoReference.IsLoaded)
            {
                photoInfo.orderInfoReference.Load();
            }
            else
            {
                photoInfo.orderInfoReference.Load(System.Data.Objects.MergeOption.OverwriteChanges);
            }
            
            orderInfo currProduct = photoInfo.orderInfo;
            if (currProduct.ProductType == (int)OrderInfoType.InnerReturn)
            {
                #region 返单

                //orderInfo parentProduct = _dal.GetProductById(currProduct.ParentProductId);
                orderInfo parentProduct = dataBase.orderInfo.FirstOrDefault(p => p.OrderProductId == currProduct.ParentProductId); ;
                //Grid gridNow = _dal.GetGridByProductId(parentProduct.OrderProductId);//副产品
                //Grid gridChild = _dal.GetGridByProductId(currProduct.OrderProductId);//子产品


                GetPhotoGridList();
                //Grid gridAction = _CurPhotoGridList.FirstOrDefault(p => p.SomeId == photoInfo.orderInfo.OrderProductId && p.Status == intGriduse);//取得现在使用格子信息


                Grid gridNow = _CurPhotoGridList.FirstOrDefault(p => p.SomeId == parentProduct.OrderProductId);//父产品
                Grid gridChild = _CurPhotoGridList.FirstOrDefault(p => p.SomeId == currProduct.OrderProductId);//子产品

                //Grid gridNow = dataBase.Grid.FirstOrDefault(p => p.SomeId == parentProduct.OrderProductId);//父产品
                //Grid gridChild = dataBase.Grid.FirstOrDefault(p => p.SomeId == currProduct.OrderProductId);//子产品


                if (gridNow == null && gridChild == null)//父产品已过分片结点 或者父子产品都没进格子 并且子产品先进格子，主产品流程在分片
                {
                    #region 
                    //Grid gridNew1 = _dal.GetMinUsefulGrid(inSubAreaId);
                    int intGridUseable = (int)GridStatus.useAble;
                    Grid gridNew = (dataBase.Grid.Where(string.Format("it.GridSubArea.SubAreaID={0}", inSubAreaId))).ToList().OrderBy(p => Convert.ToInt32(p.GridName.Substring(1))).FirstOrDefault(p => p.Status == intGridUseable);

                    if (gridNew.GridId == 0)
                    {

                        return 0;
                    }

                    using (TransactionScope ts = new TransactionScope())
                    {
                        //photoInfo.status=(int)PhotoStatus.FenPian;
                        //_dal.SetPhotoComplete(inPhotoBarcode);///修改父子产品的照片状态
                        this.SetPhotoComplete(inPhotoBarcode);
                        ///父子产品都没进格子 并且子产品先进格子，主产品流程在分片
                        if (!parentProduct.WorkOrderFlowList.IsLoaded)
                        {
                            parentProduct.WorkOrderFlowList.Load();

                        }

                        foreach (var wfl in parentProduct.WorkOrderFlowList.ToList())
                        {
                            if (!wfl.tb_TechReference.IsLoaded)
                            {
                                wfl.tb_TechReference.Load();
                            }
                        }

                        WorkOrderFlowList flowlist = parentProduct.WorkOrderFlowList.ToList().FirstOrDefault(p => p.tb_Tech.TechId == inCurrTechID&&(p.Status==1||p.Status==0));
                        if (flowlist != null)//如果父产品未过分片再返单
                        {
                            gridNew.SomeId = parentProduct.OrderProductId;
                            //子产品照片条码改修改（父产品相应的照片已经激活）
                            photoInfo.PhotoBarCode = "3" + string.Format("{0:D9}", photoInfo.photoId);
                        }
                        else//父产品的当前节点在分片之后
                        {
                            gridNew.SomeId = currProduct.OrderProductId;
                        }
                        gridNew.FirstEnterTime = DateTime.Now;
                        gridNew.Status = (int)GridStatus.use;
                        GridRecord gridRecordNew = new GridRecord();
                        gridRecordNew.Grid = gridNew;
                        gridRecordNew.SomeId = photoInfo.photoId;
                        gridRecordNew.Num = inNum;
                        gridRecordNew.CreateTime = DateTime.Now;
                        //gridRecordNew.users = _dal.GetUserById(inUserId);
                        //gridRecordNew.users = dataBase.users.FirstOrDefault(p => p.userID == inUserId);
                        dataBase.SaveChanges();
                        ts.Complete();
                    }
                    return gridNew.GridId;
                    #endregion
                }
                else if (gridNow == null && gridChild != null) //没有父产品格子只有子产品格子
                {

                    #region 
                    using (TransactionScope ts = new TransactionScope())
                    {
                        //photoInfo.status = (int)PhotoStatus.FenPian;//修改子产品的照片状态
                        this.SetPhotoComplete(inPhotoBarcode);

                        //GridRecord gridRecordAction = _dal.GetGridRecordByGridId(gridChild.GridId, photoInfo.photoId);
                        GridRecord gridRecordAction = dataBase.GridRecord.Where(string.Format("it.Grid.GridId={0} and it.SomeId={1}", gridChild.GridId, photoInfo.photoId)).FirstOrDefault();
                        if (gridRecordAction == null)
                        {
                            ///创建新的格子记录
                            gridRecordAction = new GridRecord();
                            //gridAction.Status = (int)GridStatus.
                            gridRecordAction.Grid = gridChild;
                            if (photoInfo.TotalNum <= gridRecordAction.Num)
                            {
                                gridRecordAction.Num = inNum; //数量限制
                            }
                            else
                            {
                                gridRecordAction.Num = (int)photoInfo.TotalNum;
                            }
                            gridRecordAction.SomeId = photoInfo.photoId;
                            gridRecordAction.CreateTime = DateTime.Now;
                            //gridRecordAction.users = dataBase.users.FirstOrDefault(p => p.userID == inUserId);
                        }
                        else
                        {

                            if (photoInfo.TotalNum < gridRecordAction.Num)
                            {
                                gridRecordAction.Num += inNum; //数量叠加  数量限制？？？
                            }

                        }

                        dataBase.SaveChanges();
                        ts.Complete();
                    }
                    return gridChild.GridId;
                    #endregion
                }
                else if (gridNow != null && gridChild == null)//将产品放入父产品格子
                {
                    #region 
                    using (TransactionScope ts = new TransactionScope())
                    {
                        this.SetPhotoComplete(inPhotoBarcode);//修改父子产品的照片状态
                        photoInfo.PhotoBarCode = "3" + string.Format("{0:D9}", photoInfo.photoId);///修改返工照片的条码
                        GridRecord gridRecordAction = dataBase.GridRecord.Where(string.Format("it.Grid.GridId={0} and it.SomeId={1}", gridNow.GridId, photoInfo.photoId)).FirstOrDefault();

                        if (gridRecordAction == null)
                        {
                            ///创建新的格子记录
                            gridRecordAction = new GridRecord();
                            //gridAction.Status = (int)GridStatus.
                            gridRecordAction.Grid = gridNow;
                            if (photoInfo.TotalNum <= gridRecordAction.Num)
                            {
                                gridRecordAction.Num = inNum; //数量限制
                            }
                            else
                            {

                                gridRecordAction.Num = (int)photoInfo.TotalNum;
                            }
                            gridRecordAction.SomeId = photoInfo.photoId;
                            gridRecordAction.CreateTime = DateTime.Now;
                            //gridRecordAction.users = dataBase.users.FirstOrDefault(p => p.userID == inUserId);
                        }
                        else
                        {

                            if (photoInfo.TotalNum < gridRecordAction.Num)
                            {
                                gridRecordAction.Num += inNum; //数量叠加  数量限制？？？
                            }

                        }

                        dataBase.SaveChanges();
                        ts.Complete();
                    }
                    return gridNow.GridId;
                    #endregion
                }
                else
                {
                    return 0;
                }

                #endregion 
            }
            else
            {
                #region 正常单

                int intGriduse = (int)GridStatus.use;
                //Grid gridAction = _dal.GetGridByProductId(photoInfo.orderInfo.OrderProductId);//取得现在使用格子信息
                GetPhotoGridList();
                Grid gridAction = _CurPhotoGridList.FirstOrDefault(p => p.SomeId == photoInfo.orderInfo.OrderProductId && p.Status == intGriduse);//取得现在使用格子信息

                //Grid gridAction = dataBase.Grid.FirstOrDefault(p => p.SomeId == photoInfo.orderInfo.OrderProductId && p.Status == intGriduse);//取得现在使用格子信息
                if (gridAction == null)//未分配格子 
                {

                    #region 分配新格子
                    //Grid gridNew = _dal.GetMinUsefulGrid(inSubAreaId);
                    int intGridUseable = (int)GridStatus.useAble;
                    Grid gridNew = (dataBase.Grid.Where(string.Format("it.GridSubArea.SubAreaID={0}", inSubAreaId))).ToList().OrderBy(p => Convert.ToInt32(p.GridName.Substring(1))).FirstOrDefault(p => p.Status == intGridUseable);
                    if (gridNew.GridId == 0)
                    {

                        return 0;
                    }

                    #region
                    using (TransactionScope ts = new TransactionScope())
                    {
                        //_dal.SetPhotoComplete(inPhotoBarcode);//修改照片状态
                        photoInfo.status = (int)PhotoStatus.FenPian;

                        gridNew.SomeId = photoInfo.orderInfo.OrderProductId;
                        gridNew.FirstEnterTime = DateTime.Now;
                        gridNew.Status = (int)GridStatus.use;
                        GridRecord gridRecordNew = new GridRecord();
                        gridRecordNew.Grid = gridNew;
                        gridRecordNew.SomeId = photoInfo.photoId;
                        gridRecordNew.Num = inNum;
                        gridRecordNew.CreateTime = DateTime.Now;
                        //gridRecordNew.users = dataBase.users.FirstOrDefault(p => p.userID == inUserId);
                        dataBase.SaveChanges();
                        ts.Complete();
                    }
                    #endregion


                    return gridNew.GridId;

                    #endregion

                }
                else//已分配
                {
                    #region
                    using (TransactionScope ts = new TransactionScope())
                    {
                        //_dal.SetPhotoComplete(inPhotoBarcode);//修改照片状态
                        photoInfo.status = (int)PhotoStatus.FenPian;

                        //GridRecord gridRecordAction = _dal.GetGridRecordByGridId(gridAction.GridId, photoInfo.photoId);
                        GridRecord gridRecordAction = dataBase.GridRecord.Where(string.Format("it.Grid.GridId={0} and it.SomeId={1}", gridAction.GridId, photoInfo.photoId)).FirstOrDefault();
                        //GridRecord gridRecordAction;
                        if (gridRecordAction == null)
                        {
                            ///创建新的格子记录
                            gridRecordAction = new GridRecord();
                            //gridAction.Status = (int)GridStatus.
                            gridRecordAction.Grid = gridAction;
                            if (photoInfo.TotalNum <= gridRecordAction.Num)
                            {
                                gridRecordAction.Num = inNum; //数量限制
                            }
                            else
                            {

                                gridRecordAction.Num = (int)photoInfo.TotalNum;
                            }
                            gridRecordAction.SomeId = photoInfo.photoId;
                            gridRecordAction.CreateTime = DateTime.Now;
                            //gridRecordAction.users = dataBase.users.FirstOrDefault(p => p.userID == inUserId);
                        }
                        else
                        {

                            if (photoInfo.TotalNum < gridRecordAction.Num)
                            {
                                gridRecordAction.Num += inNum; //数量叠加  数量限制？？？
                            }

                        }

                        dataBase.SaveChanges();
                        ts.Complete();
                    }
                    return gridAction.GridId;
                    #endregion
                }

                #endregion
            }
        }

        private GridSubArea _CurSubArea;
        private List<Grid> _CurPhotoGridList;

        private void  GetPhotoGridList()//得到当前分区的所有的格子
        {
            int photoAreaType = (int)SubAreaType.Photo;
            if (_CurSubArea==null)
            {
                _CurSubArea = dataBase.GridSubArea.First(ga => ga.Type == photoAreaType);
            }

            if (_CurSubArea != null)
            {
                if (!_CurSubArea.Grid.IsLoaded)
                {
                    _CurSubArea.Grid.Load();
                }
                else
                {
                    _CurSubArea.Grid.Load(System.Data.Objects.MergeOption.OverwriteChanges);
                }
            }

            _CurPhotoGridList= _CurSubArea.Grid.ToList();
        }


        private void SetPhotoComplete(string inPhotoBarcode)
        {
            //_dal.SetPhotoComplete(inPhotoBarcode);///修改父子产品的照片状态
            List<photoInfo> listPhoto = dataBase.photoInfo.Where(p => p.PhotoBarCode == inPhotoBarcode).ToList();
            foreach (photoInfo photo in listPhoto)
            {
                photo.status = (int)PhotoStatus.FenPian;
            }
        }
        /// <summary>
        ///  主单返单照片是否打印完成
        /// </summary>
        /// <param name="inBarCode"></param>
        /// <returns></returns>
        public int CheckPhoto(string inBarCode)
        {
            //photoInfo photoInfo = _dal.GetPhotoByBarCode(inBarCode); //查找已打印的照片信息
            //photoInfo photoF = _dal.GetFanDanPhotoByBarCode(inBarCode); //查找已打印的返单照片信息
            int st1 = (int)PhotoStatus.Printed;
            int st2 = (int)PhotoStatus.FenPian;
            int st3 = (int)PhotoStatus.PhotoInnerReturn;

            //photoInfo pi = dataBase.photoInfo.FirstOrDefault(p => p.PhotoBarCode == inBarCode && (p.status == st1 || p.status == st2));
            //photoInfo pi = dataBase.photoInfo.FirstOrDefault(p => p.PhotoBarCode == inBarCode);

            //photoInfo photoF = dataBase.photoInfo.FirstOrDefault(p => p.PhotoBarCode == inBarCode && p.status == st3);
            //if (pi == null)
            //{
            //    if (photoF == null)
            //    {
            //        return -1;//照片不存在或者未打印
            //    }
            //    else
            //    {
            //        return -2;//在返单中
            //    }

            //}
            //else
            //{
            //    return 1;//有照片已经打印不管主单还是返单

            //}
            photoInfo pi = dataBase.photoInfo.FirstOrDefault(p => p.PhotoBarCode == inBarCode);
            if (pi == null)
            {
                return -1;//照片不存在
            }
            else
            {
                if (pi.status == st1 || pi.status == st2)
                {
                    return 1;
                }
                else
                {
                    using (newSampleYPDBEntities DB = new newSampleYPDBEntities())
                    {
                        pi = DB.photoInfo.FirstOrDefault(p => p.PhotoBarCode == inBarCode);
                    }
                    if (pi.status == st1 || pi.status == st2)
                    {
                        return 1;
                    }
                    else if (pi.status == (int)PhotoStatus.PhotoInnerReturn)
                    {
                        return 1;//照片反单中
                    }
                    else
                    {
                        return -3; //照片未打印
                    }
                }
            }
        }




        /// <summary>
        /// 强制打印时检查产品流程
        /// </summary>
        /// <param name="inProductId"></param>
        /// <param name="inCurrTech"></param>
        /// <returns></returns>
        public bool checkIsCurraTech(int inProductId, int inCurrTech)
        {
            // orderInfo product = _dal.GetProductById(inProductId);
            orderInfo product = dataBase.orderInfo.Include("WorkOrderFlowList").FirstOrDefault(p => p.OrderProductId == inProductId);
            if (!product.WorkOrderFlowList.IsLoaded)
            {
                product.WorkOrderFlowList.Load();
            }
            else
            {
                product.WorkOrderFlowList.Load(System.Data.Objects.MergeOption.OverwriteChanges);
            }
            List<WorkOrderFlowList> flowLists = product.WorkOrderFlowList.ToList();
            int status = (int)OrderFlowListStatus.Useable;
            WorkOrderFlowList flow = flowLists.Where(p => p.Status == status).FirstOrDefault();

            if (flow == null)
            {
                return false;
            }
            else
            {
                if (!flow.tb_TechReference.IsLoaded)
                {
                    flow.tb_TechReference.Load();
                }
                if (flow.tb_Tech.TechId == inCurrTech)
                {
                    return true;
                }
                return false;
            }

        }
        /// <summary>
        ///  是否复打
        /// </summary>
        /// <param name="inBarCode"></param>
        /// <returns></returns>
        public int IsRePrint(string inBarCode, int inCurrTech, out int rpProductId)
        {
            rpProductId = 0;
            // photoInfo photoInfo = _dal.GetPhotoByBarCode(inBarCode); //照片信息
            photoInfo photoInfo = dataBase.photoInfo.Where(p => p.PhotoBarCode == inBarCode).OrderByDescending(p=>p.photoId).FirstOrDefault(); //照片信息
            if (photoInfo == null)
            {
                rpProductId = 0;
                return -1;
            }
            else
            {
                photoInfo.orderInfoReference.Load();
                orderInfo product = photoInfo.orderInfo;
                if (!product.WorkOrderFlowList.IsLoaded)
                {
                    product.WorkOrderFlowList.Load();
                }
                else
                {
                    dataBase.Refresh(System.Data.Objects.RefreshMode.StoreWins, product.WorkOrderFlowList);
                }

                //DALBase.Refresh(System.Data.Objects.RefreshMode.StoreWins, product.WorkOrderFlowList);


                foreach (var item in product.WorkOrderFlowList)
                {
                    if (!item.tb_TechReference.IsLoaded)
                    {
                        item.tb_TechReference.Load();
                    }
                    //break;
                }


                //List<WorkOrderFlowList> flowLists = product.WorkOrderFlowList.Where(p => p.tb_Tech.TechId == inCurrTech).ToList();
                //foreach (WorkOrderFlowList list in flowLists)
                //{
                //    if (list.Status == (int)OrderFlowListStatus.Complete)
                //    {
                //        rpProductId = product.OrderProductId;
                //        return true;
                //    }
                //}
                //rpProductId = 0;
                int status = (int)OrderFlowListStatus.Complete;
                WorkOrderFlowList wfl = product.WorkOrderFlowList.FirstOrDefault(p => p.tb_Tech.TechId == inCurrTech && p.Status == status);
                if (wfl != null)
                {
                    rpProductId = product.OrderProductId;
                    return 1;
                }
                return 0;
            }


        }

        /// <summary>
        /// 取得未分配数量
        /// </summary>
        /// <param name="inPhototId"></param>
        /// <param name="inGriId"></param>
        /// <returns></returns>
        public int LeavePhotoNum(string inBarCode)
        {
            photoInfo photoInfo = dataBase.photoInfo.FirstOrDefault(p => p.PhotoBarCode == inBarCode); //照片信息
            if (!photoInfo.orderInfoReference.IsLoaded)
            {
                photoInfo.orderInfoReference.Load();
            }
            int status = (int)GridStatus.use;
            Grid gridAction = dataBase.Grid.FirstOrDefault(p => p.SomeId == photoInfo.orderInfo.OrderProductId && p.Status == status);
            if (gridAction != null)
            {
                //GridRecord recorde = _dal.GetGridRecordByGridId(gridAction.GridId, photoInfo.photoId);
                GridRecord recorde = dataBase.GridRecord.Where(string.Format("it.Grid.GridId={0} and it.SomeId={1}", gridAction.GridId, photoInfo.photoId)).FirstOrDefault();
                if (recorde != null)
                {
                    return (int)photoInfo.TotalNum - recorde.Num;
                }
                else
                {

                    return (int)photoInfo.TotalNum;
                }
            }
            else
            {
                return (int)photoInfo.TotalNum;
            }

        }

        /// <summary>
        /// 更新显示
        /// </summary>
        /// <param name="inGridId"></param>
        /// <returns></returns>
        public OrderInfo_Info UpdateGrid(int inGridId)
        {
            List<Grid> grids = new List<Grid>();
            //Grid grid = _dal.GetGridById(inGridId);
            GetPhotoGridList();
            Grid grid =this._CurPhotoGridList .FirstOrDefault(p => p.GridId == inGridId);
            //Grid grid = dataBase.Grid.FirstOrDefault(p => p.GridId == inGridId);
            //grids.Add(grid);
            //return ChangerToView(grids).First();

            orderInfo product = dataBase.orderInfo.FirstOrDefault(p => p.OrderProductId == grid.SomeId);
            if (grid.SomeId<0)
            {
                WriteLogForCheck.WriteLogFile("格子ID：" + inGridId.ToString() + "但SOMEID：" + grid.SomeId.ToString());
            }
            OrderInfo_Info oi = new OrderInfo_Info() { OrderProductId = product.OrderProductId, OrderProductCode = product.OrderProductCode, OrderProductName = product.OrderProductName };
            return oi;
        }
        /// <summary>
        /// 清零格子
        /// </summary>
        /// <param name="inGridId"></param>
        public void ClearGrid(int inGridId, int inProductId)
        {
            ///1.检查该格子产品是否分片完毕
            orderInfo product = dataBase.orderInfo.FirstOrDefault(p => p.OrderProductId == inProductId);
            if (!product.photoInfo.IsLoaded)
            {
                product.photoInfo.Load();
            }
            List<photoInfo> photoInfos = product.photoInfo.ToList();
            bool isComplete = true;
            foreach (photoInfo list in photoInfos)
            {
                if (list.status != (int)PhotoStatus.FenPian)
                {
                    isComplete = false;
                    break;
                }

            }
            using (TransactionScope ts = new TransactionScope())
            {
                if (!isComplete)
                {
                    ///还原照片状态
                    foreach (photoInfo list in photoInfos)
                    {
                        list.status = (int)PhotoStatus.Printed;
                        ///还原GridRecord状态 删除当前记录

                        ////   GridRecord gridRecord = _dal.GetGridRecordByGridId(inGridId, list.photoId);
                        //GridRecord gridRecord = dataBase.GridRecord.Where(string.Format("it.Grid.GridId={0} and it.SomeId={1}", inGridId, list.photoId)).FirstOrDefault();
                        //if (gridRecord != null)
                        //{
                        //    dataBase.DeleteObject(gridRecord);
                        //}

                    }


                }
                //Grid grid = _dal.GetGridById(inGridId);
                //Grid grid = dataBase.Grid.FirstOrDefault(p => p.GridId == inGridId);
                GetPhotoGridList();
                Grid grid = this._CurPhotoGridList.FirstOrDefault(p => p.GridId == inGridId);
                if (!grid.GridRecord.IsLoaded)
                {
                    grid.GridRecord.Load();
                }
                List<GridRecord> recordList = grid.GridRecord.ToList();
                foreach (GridRecord record in recordList)
                {
                    dataBase.DeleteObject(record);
                }

                grid.FirstEnterTime = Convert.ToDateTime("2000-01-01");
                grid.SomeId = 0;
                grid.Status = (int)GridStatus.useAble;
                dataBase.SaveChanges();
                ts.Complete();
            }
        }
        /// <summary>
        /// 改变照片的状态为完成
        /// </summary>
        /// <param name="inGridId"></param>
        /// <param name="inProductId"></param>
        public void CompleteGridPhoto(int inGridId, int inProductId)
        {
            orderInfo product = dataBase.orderInfo.FirstOrDefault(p => p.OrderProductId == inProductId);
            if (!product.photoInfo.IsLoaded)
            {
                product.photoInfo.Load();
            }
            List<photoInfo> photoInfos = product.photoInfo.ToList();
            using (TransactionScope ts = new TransactionScope())
            {
                foreach (photoInfo info in photoInfos)
                {
                    info.status = (int)PhotoStatus.FenPian;
                }
                Grid grid = dataBase.Grid.FirstOrDefault(p => p.GridId == inGridId);
                grid.FirstEnterTime = Convert.ToDateTime("2000-01-01");
                grid.SomeId = 0;
                grid.Status = (int)GridStatus.useAble;
                dataBase.SaveChanges();
                ts.Complete();
            }

        }
        /// <summary>
        /// 改变分区状态
        /// </summary>
        /// <param name="inSubAreaId"></param>
        /// <param name="isUseful"></param>
        public void ChangeSubAreasUsed(int inSubAreaId, Boolean isUseful)
        {
            //GridSubArea subArea = _dal.GetOneSunAreaById(inSubAreaId);
            GridSubArea subArea = dataBase.GridSubArea.FirstOrDefault(p => p.SubAreaID == inSubAreaId);
            subArea.isUseful = isUseful;
            dataBase.SaveChanges();
        }
        /// <summary>
        /// 检查是否要打印
        /// </summary>
        /// <param name="inGrid"></param>
        /// <param name="inProductId"></param>
        /// <returns></returns>
        public bool IsPrint(int inGrid, int inProductId)
        {
            //List<photoInfo> photoInfos = _dal.GetPhotoByProductId(inProductId);
            //foreach (photoInfo list in photoInfos)
            //{
            //    //GridRecord record = _dal.GetGridRecordByGridId(inGrid, list.photoId);
            //    //if (record==null||record.Num != list.TotalNum)
            //    //{
            //    //    return true;
            //    //}
            //}

            //return true;

            orderInfo oi = dataBase.orderInfo.FirstOrDefault(p => p.OrderProductId == inProductId);
            if (!oi.photoInfo.IsLoaded)
            {
                oi.photoInfo.Load();
            }
            else
            {
                oi.photoInfo.Load(System.Data.Objects.MergeOption.OverwriteChanges);
            }


            photoInfo pi = oi.photoInfo.FirstOrDefault(p => p.status != (int)PhotoStatus.FenPian);
            if (pi != null)
            {
                return false;
            }
            else//为空就说明全部分片
            {
                using (TransactionScope ts = new TransactionScope())
                {
                    //就改变格子的状态
                    //GridDAL gdal = new GridDAL();
                    //Grid g = gdal.GetOneById(inGrid);
                    Grid g = dataBase.Grid.FirstOrDefault(p => p.GridId == inGrid);
                    g.SomeId = 0;
                    g.Status = (int)GridStatus.useAble;

                    if (!g.GridRecord.IsLoaded)
                    {
                        g.GridRecord.Load();
                    }
                    List<GridRecord> recordList = g.GridRecord.ToList();
                    foreach (GridRecord record in recordList)
                    {
                        dataBase.DeleteObject(record);
                    }

                    //添加内部返单的处理
                    //orderInfo currProduct = _dal.GetProductById(inProductId);
                    if (oi.ProductType == (int)OrderInfoType.InnerReturn)
                    {

                        ///修改新产品的照片barcode
                        foreach (photoInfo list in oi.photoInfo)
                        {

                            list.PhotoBarCode = "3" + string.Format("{0:D9}", list.photoId);
                        }
                    }
                    dataBase.SaveChanges();
                    ts.Complete();
                }
                return true;
            }

        }

        /// <summary>
        /// 检查是否要打印
        /// </summary>
        /// <param name="inGrid"></param>
        /// <param name="inProductId"></param>
        /// <returns></returns>
        public int IsPrintInt(int inGrid, int inProductId)
        {



            orderInfo oi = dataBase.orderInfo.FirstOrDefault(p => p.OrderProductId == inProductId);
            if (!oi.photoInfo.IsLoaded)
            {
                oi.photoInfo.Load();
            }
            else
            {
                oi.photoInfo.Load(System.Data.Objects.MergeOption.OverwriteChanges);
            }

            int photoFenPian = (int)PhotoStatus.FenPian;
            List<photoInfo> pi = oi.photoInfo.Where(p => p.status != photoFenPian).ToList();
            if (pi.Count() > 0)
            {
                return pi.Count();
            }
            else//为空就说明全部分片
            {
                using (TransactionScope ts = new TransactionScope())
                {
                    //就改变格子的状态                  
                    Grid g = dataBase.Grid.FirstOrDefault(p => p.GridId == inGrid);
                    g.SomeId = 0;
                    g.Status = (int)GridStatus.useAble;

                    //添加内部返单的处理
                    //orderInfo currProduct = _dal.GetProductById(inProductId);
                    if (oi.ProductType == (int)OrderInfoType.InnerReturn)
                    {
                        //orderInfo oldProduct = _dal.GetProductById(oi.ParentProductId);
                        //oldProduct.photoInfo.Load();
                        //currProduct.photoInfo.Load();
                        //List<photoInfo> photoInfoParent = oldProduct.photoInfo.ToList();
                        //foreach (photoInfo list in photoInfoParent)
                        //{
                        //    list.status = (int)PhotoStatus.FenPian;
                        //}
                        //List<photoInfo> photoInfoChild = oi.photoInfo.ToList();
                        ///修改新产品的照片barcode
                        foreach (photoInfo list in oi.photoInfo)
                        {
                            //string photoId = list.photoId.ToString();
                            //string strBarcode = "3";

                            //for (int i = 0; i < 9 - photoId.Length; i++)
                            //{
                            //    strBarcode += "0";
                            //}
                            //list.PhotoBarCode = strBarcode + photoId;
                            list.PhotoBarCode = "3" + string.Format("{0:D9}", list.photoId);
                        }
                    }
                    dataBase.SaveChanges();
                    ts.Complete();
                }
                return 0;
            }

        }
        /// <summary>
        /// 结束节点激活下一个节点
        /// </summary>
        /// <param name="inCurrTechId"></param>
        /// <param name="inOperId"></param>
        /// <param name="inProductId"></param>
        public string OverCurrTech(int inCurrTechId, int inOperId, int inProductId)
        {
            WorkFlowListBLL flowListBll = new WorkFlowListBLL();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                string rtnNextFlowName = "";
                orderInfo oi = db.orderInfo.FirstOrDefault(p => p.OrderProductId == inProductId);

                if (!flowListBll.OverCurTech(8, inOperId, oi, db, out  rtnNextFlowName)) //分片独立的激活
                {
                    WriteLogForCheck.WriteLogFile("出错时产品ID："+inProductId.ToString());
                    return "error";
                }
                else
                {
                    return rtnNextFlowName;
                }
            }

            //WorkFlowListBLL.OverCurTech(inCurrTechId, inOperId, inProductId);
        }

        /// <summary>
        /// 取得打印报表数据
        /// </summary>
        /// <param name="inGridId"></param>
        /// <param name="inProduct"></param>
        public DataSet GetReportdata(int inGridId, int inProduct, string inGridName)
        {
            // orderInfo product = _dal.GetProductById(inProduct);
            orderInfo product = dataBase.orderInfo.FirstOrDefault(p => p.OrderProductId == inProduct);
            if (!product.Tb_OrderBagReference.IsLoaded)
            {
                product.Tb_OrderBagReference.Load();
            }
            if (!product.Tb_OrderBag.ShopReference.IsLoaded)
            {
                product.Tb_OrderBag.ShopReference.Load();
            }


            DataTable infoTable = CreateInfoTable();
            infoTable.TableName = "infoTable";
            DataRow rowInfo = infoTable.NewRow();
            rowInfo["BagCode"] = product.Tb_OrderBag.BagCode;
            rowInfo["BagName"] = product.Tb_OrderBag.BagName;
            rowInfo["shopName"] = product.Tb_OrderBag.Shop.shopName;
            rowInfo["OrderProductCode"] = "*" + product.OrderProductCode + "*";
            rowInfo["OrderProductName"] = product.OrderProductName;
            rowInfo["CtmName"] = product.CtmName;
            rowInfo["productNum"] = product.productNum;
            rowInfo["remark"] = product.Remark;
            rowInfo["GridName"] = inGridName;
            rowInfo["OrderTime"] = product.Tb_OrderBag.OrderTime;

            infoTable.Rows.Add(rowInfo);
            if (product.Priority >= 11)
            {
                rowInfo["Priority"] = "特急件";
            }
            else if (product.Priority < 11 && product.Priority >= 6)
            {
                rowInfo["Priority"] = "急件";
            }
            else
            {
                rowInfo["Priority"] = "";
            }

            DataTable photoTable = CreatePhotoInfoTable();
            Dictionary<string, int> photos = new Dictionary<string, int>();
            //Dictionary<string, int> photosCM = new Dictionary<string, int>();
            //List<photoInfo> photoInfos = _dal.GetPhotoByProductId(inProduct);
            if (!product.photoInfo.IsLoaded)
            {
                product.photoInfo.Load();
            }
            List<photoInfo> photoInfos = product.photoInfo.ToList();
            foreach (photoInfo list in product.photoInfo)
            {
                string photoSize = "" + Math.Round(list.Width, 2) + "×" + Math.Round(list.Height, 2) + "in(" + Math.Round(list.Width * 2.54, 2) + "×" + Math.Round(list.Height * 2.54, 2) + "cm)";
                string photoSize1 = "" + Math.Round(list.Height, 2) + "×" + Math.Round(list.Width, 2) + "in(" + Math.Round(list.Height * 2.54, 2) + "×" + Math.Round(list.Width * 2.54, 2) + "cm)";

                //string photoSizeCM = Math.Round(list.Width * 2.54, 2) + "×" + Math.Round(list.Height, 2);
                if (photos.Keys.Contains(photoSize))
                {
                    photos[photoSize] += 1;
                }
                else if (photos.Keys.Contains(photoSize1))
                {
                    photos[photoSize1] += 1;
                }
                else
                {
                    photos.Add(photoSize, 1);
                    //photosCM.Add(photoSizeCM, 1);
                }
            }
            foreach (var list in photos)
            {
                DataRow row = photoTable.NewRow();
                row["Size"] = list.Key;
                row["Num"] = list.Value;
                photoTable.Rows.Add(row);

            }
            photoTable.TableName = "photoTable";

            if (!product.WorkOrderFlowList.IsLoaded)
            {
                product.WorkOrderFlowList.Load();
            }
            //List<WorkOrderFlowList> flows = _dal.GetAllFlowByProductId(inProduct).OrderBy(p => p.WorkOrder).ToList();
            string strFlow = string.Empty;
            foreach (WorkOrderFlowList list in product.WorkOrderFlowList.OrderBy(p => p.WorkOrder))
            {
                if (!list.tb_TechReference.IsLoaded)
                {
                    list.tb_TechReference.Load();
                }
                strFlow = strFlow + list.tb_Tech.TechName + "->";
            }
            strFlow = strFlow.Trim("->".ToCharArray());
            DataTable flowTable = CreateTechFlow();
            //foreach (WorkOrderFlowList list in flows)
            //{
            //    if (!list.tb_TechReference.IsLoaded)
            //    {
            //        list.tb_TechReference.Load();
            //    }
            //    users user = _dal.GetUserById(list.UserId);
            //    DataRow row = flowTable.NewRow();
            //    row["TechName"] = list.tb_Tech.TechName;
            //    if (user != null)
            //    {
            //        row["UserName"] = user.UserName;
            //    }
            //    else
            //    {
            //        row["UserName"] = "";
            //    }
            //    flowTable.Rows.Add(row);
            //}
            DataRow rowt = flowTable.NewRow();
            rowt["TechName"] = strFlow;
            rowt["UserName"] = "0";
            flowTable.Rows.Add(rowt);
            flowTable.TableName = "flowTable";

            DataSet ds = new DataSet();
            ds.Tables.Add(photoTable);
            ds.Tables.Add(infoTable);
            ds.Tables.Add(flowTable);

            return ds;
        }
        /// <summary>
        /// 取得打印报表数据
        /// </summary>
        /// <param name="inGridId"></param>
        /// <param name="inProduct"></param>
        public DataSet GetReportdataBK(int inGridId, int inProduct, string inGridName)
        {
            // orderInfo product = _dal.GetProductById(inProduct);
            orderInfo_BK product = dataBase.orderInfo_BK.FirstOrDefault(p => p.OrderProductId == inProduct);
            if (!product.Tb_OrderBag_BKReference.IsLoaded)
            {
                product.Tb_OrderBag_BKReference.Load();
            }
            if (!product.Tb_OrderBag_BK.ShopReference.IsLoaded)
            {
                product.Tb_OrderBag_BK.ShopReference.Load();
            }


            DataTable infoTable = CreateInfoTable();
            infoTable.TableName = "infoTable";
            DataRow rowInfo = infoTable.NewRow();
            rowInfo["BagCode"] = product.Tb_OrderBag_BK.BagCode;
            rowInfo["BagName"] = product.Tb_OrderBag_BK.BagName;
            rowInfo["shopName"] = product.Tb_OrderBag_BK.Shop.shopName;
            rowInfo["OrderProductCode"] = "*" + product.OrderProductCode + "*";
            rowInfo["OrderProductName"] = product.OrderProductName;
            rowInfo["CtmName"] = product.CtmName;
            rowInfo["productNum"] = product.productNum;
            rowInfo["remark"] = product.Remark;
            rowInfo["GridName"] = inGridName;
            rowInfo["OrderTime"] = product.Tb_OrderBag_BK.OrderTime;

            infoTable.Rows.Add(rowInfo);
            if (product.Priority >= 11)
            {
                rowInfo["Priority"] = "特急件";
            }
            else if (product.Priority < 11 && product.Priority >= 6)
            {
                rowInfo["Priority"] = "急件";
            }
            else
            {
                rowInfo["Priority"] = "";
            }

            DataTable photoTable = CreatePhotoInfoTable();
            Dictionary<string, int> photos = new Dictionary<string, int>();
            //Dictionary<string, int> photosCM = new Dictionary<string, int>();
            //List<photoInfo> photoInfos = _dal.GetPhotoByProductId(inProduct);
            if (!product.photoInfo_BK.IsLoaded)
            {
                product.photoInfo_BK.Load();
            }
            List<photoInfo_BK> photoInfos = product.photoInfo_BK.ToList();
            foreach (photoInfo_BK list in product.photoInfo_BK)
            {
                string photoSize = "" + Math.Round(list.Width, 2) + "×" + Math.Round(list.Height, 2) + "in(" + Math.Round(list.Width * 2.54, 2) + "×" + Math.Round(list.Height * 2.54, 2) + "cm)";
                string photoSize1 = "" + Math.Round(list.Height, 2) + "×" + Math.Round(list.Width, 2) + "in(" + Math.Round(list.Height * 2.54, 2) + "×" + Math.Round(list.Width * 2.54, 2) + "cm)";

                //string photoSizeCM = Math.Round(list.Width * 2.54, 2) + "×" + Math.Round(list.Height, 2);
                if (photos.Keys.Contains(photoSize))
                {
                    photos[photoSize] += 1;
                }
                else if (photos.Keys.Contains(photoSize1))
                {
                    photos[photoSize1] += 1;
                }
                else
                {
                    photos.Add(photoSize, 1);
                    //photosCM.Add(photoSizeCM, 1);
                }
            }
            foreach (var list in photos)
            {
                DataRow row = photoTable.NewRow();
                row["Size"] = list.Key;
                row["Num"] = list.Value;
                photoTable.Rows.Add(row);

            }
            photoTable.TableName = "photoTable";

            if (!product.WorkOrderFlowList_BK.IsLoaded)
            {
                product.WorkOrderFlowList_BK.Load();
            }
            //List<WorkOrderFlowList> flows = _dal.GetAllFlowByProductId(inProduct).OrderBy(p => p.WorkOrder).ToList();
            string strFlow = string.Empty;
            foreach (WorkOrderFlowList_BK list in product.WorkOrderFlowList_BK.OrderBy(p => p.WorkOrder))
            {
                if (!list.tb_TechReference.IsLoaded)
                {
                    list.tb_TechReference.Load();
                }
                strFlow = strFlow + list.tb_Tech.TechName + "->";
            }
            strFlow = strFlow.Trim("->".ToCharArray());
            DataTable flowTable = CreateTechFlow();
            //foreach (WorkOrderFlowList list in flows)
            //{
            //    if (!list.tb_TechReference.IsLoaded)
            //    {
            //        list.tb_TechReference.Load();
            //    }
            //    users user = _dal.GetUserById(list.UserId);
            //    DataRow row = flowTable.NewRow();
            //    row["TechName"] = list.tb_Tech.TechName;
            //    if (user != null)
            //    {
            //        row["UserName"] = user.UserName;
            //    }
            //    else
            //    {
            //        row["UserName"] = "";
            //    }
            //    flowTable.Rows.Add(row);
            //}
            DataRow rowt = flowTable.NewRow();
            rowt["TechName"] = strFlow;
            rowt["UserName"] = "0";
            flowTable.Rows.Add(rowt);
            flowTable.TableName = "flowTable";

            DataSet ds = new DataSet();
            ds.Tables.Add(photoTable);
            ds.Tables.Add(infoTable);
            ds.Tables.Add(flowTable);

            return ds;
        }
        /// <summary>
        ///  基本信息表
        /// </summary>
        /// <returns></returns>
        public DataTable CreateInfoTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("BagCode", typeof(string));
            table.Columns.Add("BagName", typeof(string));
            table.Columns.Add("shopName", typeof(string));
            table.Columns.Add("OrderProductCode", typeof(string));
            table.Columns.Add("OrderProductName", typeof(string));
            table.Columns.Add("CtmName", typeof(string));
            table.Columns.Add("productNum", typeof(int));
            table.Columns.Add("remark", typeof(string));
            table.Columns.Add("GridName", typeof(string));
            table.Columns.Add("Priority", typeof(string));
            table.Columns.Add("OrderTime", typeof(string));
            return table;

        }
        /// <summary>
        /// 照片信息
        /// </summary>
        /// <returns></returns>
        public DataTable CreatePhotoInfoTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("Size", typeof(string));
            //table.Columns.Add("Size1", typeof(string));
            table.Columns.Add("Num", typeof(int));
            return table;
        }
        /// <summary>
        /// 流程信息
        /// </summary>
        /// <returns></returns>
        public DataTable CreateTechFlow()
        {
            DataTable table = new DataTable();
            table.Columns.Add("TechName", typeof(string));
            table.Columns.Add("UserName", typeof(string));
            return table;
        }
        //public DataTable CreateTechFlow()
        //{
        //    DataTable table = new DataTable();
        //    table.Columns.Add("TechName", typeof(string));
        //    return table;
        //}
        /// <summary>
        /// 获得下一个流程的名称
        /// </summary>
        /// <param name="inProductId"></param>
        /// <returns></returns>
        public string GetNextFlowName(int inProductId)
        {
            //return _dal.GetNextFlowName(inProductId);
            int stutas = (int)OrderInfoStatus.Doing;
            string techName = "";
            orderInfo oi = dataBase.orderInfo.FirstOrDefault(o => o.OrderProductId == inProductId);
            if (oi != null)
            {
                if (oi.ProductType == (int)OrderInfoType.InnerReturn)
                {
                    return "";
                }
                //oi.WorkOrderFlowList.Load(MergeOption.OverwriteChanges);
                if (!oi.WorkOrderFlowList.IsLoaded)
                {
                    oi.WorkOrderFlowList.Load();
                }
                else
                {
                    oi.WorkOrderFlowList.Load(System.Data.Objects.MergeOption.OverwriteChanges);
                }
                WorkOrderFlowList wofl = oi.WorkOrderFlowList.ToList().FirstOrDefault(wf => wf.Status == stutas);
                if (wofl != null)
                {
                    if (!wofl.tb_TechReference.IsLoaded)
                    {
                        wofl.tb_TechReference.Load();
                    }
                    techName = wofl.tb_Tech.TechName;
                }
            }
            return techName;
        }

        public void RushDateBase()
        {
            _dal.RushDateBase();

        }

        public void GetShopInfo(PhotoGridOrderHeadInfo photoGridOrderHeadInfo)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 根据照片提高大板加急 当格子中剩余照片少于等于inNum时
        /// </summary>
        /// <param name="photoBarCode"></param>
        public void AdvanceBoard(int inSubAreaId, int inNum)
        {


            List<Grid> gridList =
                dataBase.Grid.Where(p => p.GridSubArea.SubAreaID == inSubAreaId && p.SomeId != 0 && p.Status != 0).ToList();
            //List<orderInfo> productList=new List<orderInfo>();
            System.Transactions.TransactionOptions options = new TransactionOptions();
            options.Timeout = new TimeSpan(0, 0, 600);
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, options))
            {
                foreach (Grid info in gridList)
                {
                    orderInfo oi = dataBase.orderInfo.Where(p => p.OrderProductId == info.SomeId).FirstOrDefault();
                    if (!oi.photoInfo.IsLoaded)
                    {
                        oi.photoInfo.Load();
                    }

                    int photoStatus = (int)PhotoStatus.PingBan;
                    int photoStatus2 = (int)PhotoStatus.NoDistributePrinter;
                    int photoStatus3 = (int)PhotoStatus.DistributedPrinter;
                    int photoStatus4 = (int)PhotoStatus.PingBanInd;
                    List<photoInfo> photoInfos = oi.photoInfo.Where(p => p.status == photoStatus || p.status == photoStatus2 || p.status == photoStatus3 || p.status == photoStatus4).ToList();
                    if (photoInfos.Count() < inNum)
                    {
                        foreach (photoInfo photo in photoInfos)
                        {
                            if (!photo.picMakeUp.IsLoaded)
                            {
                                photo.picMakeUp.Load();
                            }
                            if (photo.picMakeUp != null)
                            {
                                photo.picMakeUp.FirstOrDefault().BoardReference.Load();
                                Board board = photo.picMakeUp.FirstOrDefault().Board;
                                if ((board.status == (int)EnumBoardStatus.waitProduct || board.status == (int)EnumBoardStatus.WaitingPrint) && board.printPriority != 11)
                                {
                                    board.printPriority = 11;
                                    board.status = (int)EnumBoardStatus.waitProduct;
                                }
                            }
                            photo.status2 = (int)PhotoStatus2.advance;
                        }

                    }
                    if (inNum == 0)
                    {
                        foreach (photoInfo photo in photoInfos)
                        {
                            if (!photo.picMakeUp.IsLoaded)
                            {
                                photo.picMakeUp.Load();
                            }
                            if (photo.picMakeUp != null)
                            {
                                photo.picMakeUp.FirstOrDefault().BoardReference.Load();
                                Board board = photo.picMakeUp.FirstOrDefault().Board;
                                if ((board.status == (int)EnumBoardStatus.waitProduct || board.status == (int)EnumBoardStatus.WaitingPrint) && board.printPriority != 11)
                                {
                                    board.printPriority = 11;
                                    board.status = (int)EnumBoardStatus.waitProduct;
                                }
                            }
                            photo.status2 = (int)PhotoStatus2.advance;
                        }
                    }

                }
                dataBase.SaveChanges();
                ts.Complete();
            }
            //}
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="inProductList"></param>
        public void AdvanceGrid(string inProductList)
        {

            string[] ArrProduct = inProductList.Split(',');
            //using (newSampleYPDBEntities ds = new newSampleYPDBEntities())
            //{
            System.Transactions.TransactionOptions options = new TransactionOptions();
            options.Timeout = new TimeSpan(0, 0, 600);
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, options))
            {
                foreach (string info in ArrProduct)
                {
                    int productid = Convert.ToInt32(info);
                    orderInfo oi = dataBase.orderInfo.Where(p => p.OrderProductId == productid).FirstOrDefault();
                    if (!oi.photoInfo.IsLoaded)
                    {
                        oi.photoInfo.Load();
                    }
                    int photoStatus = (int)PhotoStatus.PingBan;
                    int photoStatus2 = (int)PhotoStatus.NoDistributePrinter;
                    int photoStatus3 = (int)PhotoStatus.DistributedPrinter;
                    int photoStatus4 = (int)PhotoStatus.PingBanInd;
                    List<photoInfo> photoInfos = oi.photoInfo.Where(p => p.status == photoStatus || p.status == photoStatus2 || p.status == photoStatus3 || p.status == photoStatus4).ToList();

                    foreach (photoInfo photo in photoInfos)
                    {
                        if (!photo.picMakeUp.IsLoaded)
                        {
                            photo.picMakeUp.Load();
                        }
                        if (photo.picMakeUp != null)
                        {
                            photo.picMakeUp.FirstOrDefault().BoardReference.Load();
                            Board board = photo.picMakeUp.FirstOrDefault().Board;
                            if ((board.status == (int)EnumBoardStatus.waitProduct || board.status == (int)EnumBoardStatus.WaitingPrint) && board.printPriority != 11)
                            {
                                board.printPriority = 11;
                                board.status = (int)EnumBoardStatus.waitProduct;

                            }
                        }
                        photo.status2 = (int)PhotoStatus2.advance;
                    }


                }
                dataBase.SaveChanges();
                ts.Complete();
            }
            //}

        }
        /// <summary>
        /// 获取商户
        /// </summary>
        /// <returns></returns>
        public List<Shop_Info> GetShopList()
        {
            List<Shop_Info> list = new List<Shop_Info>();
            List<Shop> shopList = dataBase.Shop.OrderBy(p => p.shopName).ToList();
            foreach (Shop shop in shopList)
            {
                Shop_Info info = new Shop_Info() { ShopId = shop.ShopId, ShopName = shop.shopName };
                list.Add(info);
            }
            return list;
        }

        public string GetShopNameByOrderId(int inOrderid)
        {
            //return _dal.GetShopNameByOrderId(inOrderid);
            orderInfo oi = dataBase.orderInfo.Where(p => p.OrderProductId == inOrderid).FirstOrDefault();
            if (!oi.Tb_OrderBagReference.IsLoaded)
            {
                oi.Tb_OrderBagReference.Load();
            }
            if (!oi.Tb_OrderBag.ShopReference.IsLoaded)
            {
                oi.Tb_OrderBag.ShopReference.Load();
            }
            return oi.Tb_OrderBag.Shop.shopName;

        }
        public List<PhotoView> GetPhotoListByOnePhotoBarcode(int photoId)
        {
            photoInfo photo = dataBase.photoInfo.FirstOrDefault(p => p.photoId == photoId);
            if (photo == null)
            {
                return null;
            }
            if (!photo.orderInfoReference.IsLoaded)
            {
                photo.orderInfoReference.Load();
            }
            orderInfo orderProduct = photo.orderInfo;
            if (orderProduct.photoInfo.IsLoaded)
            {
                orderProduct.photoInfo.Load();
            }
            if (!orderProduct.Tb_OrderBagReference.IsLoaded)
            {
                orderProduct.Tb_OrderBagReference.Load();
            }
            if (!orderProduct.Tb_OrderBag.ShopReference.IsLoaded)
            {
                orderProduct.Tb_OrderBag.ShopReference.Load();
            }
            Shop shop = orderProduct.Tb_OrderBag.Shop;
            List<PhotoView> rtnList = new List<PhotoView>();

            orderProduct.photoInfo.Load();

            List<photoInfo> photoList = orderProduct.photoInfo.ToList();
            foreach (photoInfo info in photoList)
            {
                PhotoView view = new PhotoView();
                view.PhotoInfo = new PhotoInfo_Info() { PhotoBarCode = info.PhotoBarCode, PhotoName = info.photoName, PicPath = info.picPath, PrinterId = (int)info.printerId, Remark = info.Remark, PhotoId = info.photoId, Width = info.Width, Height = info.Height, Status = info.status };

                if (!info.paperFaceReference.IsLoaded)
                {
                    info.paperFaceReference.Load();
                }
                if (!info.paperTypeReference.IsLoaded)
                {
                    info.paperTypeReference.Load();
                }
                paperFace face = info.paperFace;
                view.PaperFaceInfo = new PaperFace_Info() { Name = face.Name, PaperFaceID = face.PaperFaceID };
                paperType type = info.paperType;
                view.PaperTypeInfo = new PaperType_Info() { Name = type.Name, PaperTypeID = type.PaperTypeID };
                printer pr = dataBase.printer.FirstOrDefault(p => p.PrinterID == info.printerId);
                if (pr != null)
                {
                    view.PrinterName = pr.PName;
                }
                else
                {
                    view.PrinterName = "未分配打印机";
                }
                rtnList.Add(view);

            }
            return rtnList;


        }
        /// <summary>
        /// 取得格子头部相关详细信息
        /// </summary>
        /// <param name="inGridId"></param>
        /// <returns></returns>
        public PhotoGridOrderHeadInfo GetHeadInfo(string inBarCode)
        {
            photoInfo photo = dataBase.photoInfo.FirstOrDefault(p => p.PhotoBarCode == inBarCode);
            if (!photo.orderInfoReference.IsLoaded)
            {
                photo.orderInfoReference.Load();
            }
            orderInfo orderProduct = photo.orderInfo;
            PhotoGridOrderHeadInfo oiheadinfo = new PhotoGridOrderHeadInfo();
            if (orderProduct != null || orderProduct.OrderProductId != 0)
            {
                MINERP.DAL.PhotoRindGrid.OrderInfoDAL oiDal = new MINERP.DAL.PhotoRindGrid.OrderInfoDAL();
                oiheadinfo = oiDal.GetOrderHeadInfoById(orderProduct.OrderProductId);

            }
            return oiheadinfo;
        }


        public int GetCurrNum(int gridId)
        {
            Grid grid = dataBase.Grid.FirstOrDefault(p=>p.GridId==gridId);
            grid.GridRecord.Load();
            return grid.GridRecord.Count();

        }
    }
}
